package org.jeecg.modules.rental.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.rental.entity.RentalFaultHandle;
import org.jeecg.modules.rental.entity.RentalFaultType;
import org.jeecg.modules.rental.enums.FaultFromDictEnums;
import org.jeecg.modules.rental.enums.FaultObjTypeEnums;
import org.jeecg.modules.rental.enums.FaultStatusDictEnums;
import org.jeecg.modules.rental.mapper.RentalFaultHandleMapper;
import org.jeecg.modules.rental.mapper.RentalFaultTypeMapper;
import org.jeecg.modules.rental.service.IRentalFaultHandleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * @Description: 故障处理
 * @Author: jeecg-boot
 * @Date:   2024-07-23
 * @Version: V1.0
 */
@Service
public class RentalFaultHandleServiceImpl extends ServiceImpl<RentalFaultHandleMapper, RentalFaultHandle> implements IRentalFaultHandleService {

//    @Autowired
//    private RentalPayAccountMapper payAccountMapper;
//    @Autowired
//    private RentalAccountPackageMapper rentalAccountPackageMapper;
//    @Autowired
//    private RentalCarMapper rentalCarMapper;
//    @Autowired
//    private IControlAPI iControlAPI;

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Autowired
    private RentalFaultTypeMapper rentalFaultTypeMapper;

    @Value(value="${jeecg.uploadType}")
    private String uploadType;

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    @Override
    public IPage<RentalFaultHandle> selectJoinPage(Page page, RentalFaultHandle entity) {
        IPage<RentalFaultHandle> pageList = baseMapper.selectJoinPage(page, entity);
        if(ObjectUtil.isNotEmpty(pageList) && ObjectUtil.isNotEmpty(pageList.getRecords())){
            Set<Long> carIds = pageList.getRecords().stream().filter(a-> a.getObjType().equals(FaultObjTypeEnums.VEHICLE.getValue())).map(RentalFaultHandle::getObjId).collect(Collectors.toSet());
//            List<RentalCar> carList = rentalCarMapper.selectBatchIds(carIds);
            Set<String> faultCodeList = pageList.getRecords().stream().map(RentalFaultHandle::getFaultCode).collect(Collectors.toSet());

            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            List<RentalFaultType> faultTypeList = rentalFaultTypeMapper.selectByCode(loginUser.getOrgCode(), faultCodeList);

            pageList.getRecords().stream().forEach(item->{
                item.setObjTypeName(FaultObjTypeEnums.getEnumByValue(item.getObjType()).getLabel());
                if(FaultObjTypeEnums.VEHICLE.getValue().equals(item.getObjType())){
                    //TODO 查询车辆信息,显示故障对象
                    //item.setObjCode(rentalCar.getCarCode()+"-"+ rentalCar.getPlate());
//                    RentalCar rentalCar = carList.stream().filter(a-> a.getId().equals(item.getObjId())).findFirst().orElse(null);
//                    if(ObjectUtil.isNotEmpty(rentalCar)){
//                        item.setObjCode(rentalCar.getCarCode()+"-"+ rentalCar.getPlate());
//                    }
                }
                RentalFaultType faultType = faultTypeList.stream().filter(a-> a.getCode().equals(item.getFaultCode())).findFirst().orElse(null);
                if(ObjectUtil.isNotEmpty(faultType)){
                    item.setFaultCodeName(faultType.getName());
                }
                item.setFaultStatusName(FaultStatusDictEnums.getEnumByValue(item.getFaultStatus()).getLabel());
                item.setFaultFromName(FaultFromDictEnums.getEnumByValue(item.getFaultFrom()).getLabel());
            });
        }
        return pageList;
    }

    @Override
    public RentalFaultHandle queryById(String id) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        RentalFaultHandle rentalFaultHandle = baseMapper.selectById(id);
        rentalFaultHandle.setObjTypeName(FaultObjTypeEnums.getEnumByValue(rentalFaultHandle.getObjType()).getLabel());
        rentalFaultHandle.setFaultStatusName(FaultStatusDictEnums.getEnumByValue(rentalFaultHandle.getFaultStatus()).getLabel());
        rentalFaultHandle.setFaultFromName(FaultFromDictEnums.getEnumByValue(rentalFaultHandle.getFaultFrom()).getLabel());
        if(rentalFaultHandle.getObjType().equals(FaultObjTypeEnums.VEHICLE.getValue())){
            //TODO 查询车辆信息,显示故障对象
//            rentalFaultHandle.setObjCode(rentalCar.getCarCode()+"-"+ rentalCar.getPlate());
//            RentalCar rentalCar = rentalCarMapper.selectById(rentalFaultHandle.getObjId());
//            if(ObjectUtil.isNotEmpty(rentalCar)){
//                rentalFaultHandle.setObjCode(rentalCar.getCarCode()+"-"+ rentalCar.getPlate());
//            }
        }

        RentalFaultType faultType = rentalFaultTypeMapper.selectOneByCode(loginUser.getOrgCode(), rentalFaultHandle.getFaultCode());
        if(ObjectUtil.isNotEmpty(faultType)){
            rentalFaultHandle.setFaultCodeName(faultType.getName());
        }
        return rentalFaultHandle;
    }

    @Override
    public void faultHandle(RentalFaultHandle req, MultipartRequest files) {
        if (ObjectUtil.isEmpty(req.getAccountPackageId())){
            throw new JeecgBootException("faulthandle.service.business.logic.exception");
        }
        if (ObjectUtil.isEmpty(req.getPhone())){
            throw new JeecgBootException("faulthandle.service.please.enter.phone.number");
        }
        if (ObjectUtil.isEmpty(req.getFaultCode())){
            throw new JeecgBootException("faulthandle.service.please.select.fault.code");
        }

        //TODO 校验
//
//        RentalAccountPackage accountPackage = rentalAccountPackageMapper.selectById(req.getAccountPackageId());
//        if(ObjectUtil.isEmpty(accountPackage)){
//            throw new JeecgBootException("faulthandle.service.business.logic.exception");
//        }
//        RentalCar car = rentalCarMapper.selectById(accountPackage.getCarId());
//        if(ObjectUtil.isEmpty(car)){
//            throw new JeecgBootException("faulthandle.service.vehicle.location.info.failed");
//        }
//        Location location=iControlAPI.queryLByDeviceId(car.getCarCode());
//        if (ObjectUtil.isEmpty(location)){
//            throw new JeecgBootException("faulthandle.service.vehicle.location.info.failed");
//        }
//        RentalPayAccount payAccount = payAccountMapper.selectById(accountPackage.getAccountId());
//        if (ObjectUtil.isEmpty(payAccount)){
//            throw new JeecgBoot401Exception("faulthandle.service.please.login.first");
//        }

        //TODO 暂时注释掉
//        StringBuffer savePath = new StringBuffer();
//        files.getMultiFileMap().forEach( (name, multipartFiles)->{
//            String filePath = CommonUtils.uploadnew(multipartFiles.get(0), uploadpath, "fault", uploadType);
//            savePath.append(filePath);
//            savePath.append(";");
//        });
//        double[] gcj02 = iControlAPI.gpsToGcj02(location.getLatitude(), location.getLongitude());
//        RentalFaultHandle rentalFaultHandle = new RentalFaultHandle();
//        rentalFaultHandle.setObjId(accountPackage.getCarId());
//        rentalFaultHandle.setObjType(FaultObjTypeEnums.VEHICLE.getValue());
//        rentalFaultHandle.setFaultAttach(savePath.toString());
//        rentalFaultHandle.setLatitude(String.valueOf(gcj02[0]));
//        rentalFaultHandle.setLongitude(String.valueOf(gcj02[1]));
//        rentalFaultHandle.setFaultCode(req.getFaultCode());
//        rentalFaultHandle.setFaultDesc(req.getFaultDesc());
//        rentalFaultHandle.setFaultStatus("0");
//        rentalFaultHandle.setAccountId(payAccount.getAccountId());
//        rentalFaultHandle.setFaultReporter(payAccount.getIdentityName());
//        if(req.getPhone().contains("****")){
//            rentalFaultHandle.setPhone(payAccount.getPhone());
//        }else{
//            rentalFaultHandle.setPhone(req.getPhone());
//        }
//
//        rentalFaultHandle.setReportedDate(LocalDateTime.now());
//        rentalFaultHandle.setFaultFrom("1");
//        rentalFaultHandle.setAccountPackageId(req.getAccountPackageId());
//        rentalFaultHandle.setSysOrgCode(OrgThreadHolder.get());
//        baseMapper.insert(rentalFaultHandle);
    }

    @Override
    public void report(RentalFaultHandle req) {
      /*  RentalPayAccount account=new RentalPayAccount();
        if (req.getAccountId()!=null){
            payAccountMapper.selectById(req.getAccountId());
        }*/
//        if ("1".equals(req.getFaultFrom())){
//            if (req.getObjId()!=null){
//                RentalCar car=rentalCarMapper.selectById(req.getObjId());
//                if (car!=null){
//                    Location location=iControlAPI.queryLByDeviceId(car.getCarCode());
//                    if (location!=null){
//                        double[] gcj02 = iControlAPI.gpsToGcj02(location.getLatitude(), location.getLongitude());
//                        req.setLatitude(String.valueOf(gcj02[0]));
//                        req.setLongitude(String.valueOf(gcj02[1]));
//                    }
//                }
//
//            }
//        }
//        req.setSysOrgCode(OrgThreadHolder.get());
        /*if (account!=null){
            req.setFaultReporter(account.getAccountName());
        }*/
        baseMapper.insert(req);
    }

    @Override
    public void wxVehicleReport(RentalFaultHandle req, MultipartFile file) {
        if (ObjectUtil.isEmpty(req.getAccountPackageId())){
            throw new JeecgBootException("faulthandle.service.business.logic.exception");
        }
        if (ObjectUtil.isEmpty(req.getPhone())){
            throw new JeecgBootException("faulthandle.service.please.enter.phone.number");
        }
        if (ObjectUtil.isEmpty(req.getFaultCode())){
            throw new JeecgBootException("faulthandle.service.please.select.fault.code");
        }

        //TODO 校验
//        RentalAccountPackage accountPackage = rentalAccountPackageMapper.selectById(req.getAccountPackageId());
//        if(ObjectUtil.isEmpty(accountPackage)){
//            throw new JeecgBootException("faulthandle.service.business.logic.exception");
//        }
//        RentalCar car = rentalCarMapper.selectById(accountPackage.getCarId());
//        if(ObjectUtil.isEmpty(car)){
//            throw new JeecgBootException("faulthandle.service.vehicle.location.info.failed");
//        }
//        Location location=iControlAPI.queryLByDeviceId(car.getCarCode());
//        if (ObjectUtil.isEmpty(location)){
//            throw new JeecgBootException("faulthandle.service.vehicle.location.info.failed");
//        }
//        RentalPayAccount payAccount = payAccountMapper.selectById(accountPackage.getAccountId());
//        if (ObjectUtil.isEmpty(payAccount)){
//            throw new JeecgBoot401Exception("faulthandle.service.please.login.first");
//        }

            //TODO 暂时注释掉
//        String savePath = CommonUtils.uploadnew(file, uploadpath, "fault", uploadType);
//        double[] gcj02 = iControlAPI.gpsToGcj02(location.getLatitude(), location.getLongitude());
//        RentalFaultHandle rentalFaultHandle = new RentalFaultHandle();
//        rentalFaultHandle.setObjId(accountPackage.getCarId());
//        rentalFaultHandle.setObjType(FaultObjTypeEnums.VEHICLE.getValue());
//        rentalFaultHandle.setFaultAttach(savePath);
//        rentalFaultHandle.setLatitude(String.valueOf(gcj02[0]));
//        rentalFaultHandle.setLongitude(String.valueOf(gcj02[1]));
//        rentalFaultHandle.setFaultCode(req.getFaultCode());
//        rentalFaultHandle.setFaultDesc(req.getFaultDesc());
//        rentalFaultHandle.setFaultStatus("0");
//        rentalFaultHandle.setAccountId(payAccount.getAccountId());
//        rentalFaultHandle.setFaultReporter(payAccount.getIdentityName());
//        if(req.getPhone().contains("****")){
//            rentalFaultHandle.setPhone(payAccount.getPhone());
//        }else{
//            rentalFaultHandle.setPhone(req.getPhone());
//        }
//        rentalFaultHandle.setReportedDate(LocalDateTime.now());
//        rentalFaultHandle.setFaultFrom("1");
//        rentalFaultHandle.setAccountPackageId(req.getAccountPackageId());
//        rentalFaultHandle.setSysOrgCode(OrgThreadHolder.get());
//        baseMapper.insert(rentalFaultHandle);
    }

    @Override
    public void assignHandler(RentalFaultHandle req) {
        RentalFaultHandle rentalFaultHandle = baseMapper.selectById(req.getId());
        rentalFaultHandle.setFaultHandler(req.getFaultHandler());
        baseMapper.updateById(rentalFaultHandle);
    }


}
